package com.jalonjia.paste.service.impl;

import com.jalonjia.paste.pojo.Paste;
import com.jalonjia.paste.service.PasteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.DelayQueue;

/**
 * @author jalon
 */
@Slf4j
@Service("memoryPasteService")
@ConditionalOnProperty(value = "paste.datasource", havingValue = "memory")
public class MemoryPasteServiceImpl implements PasteService {
    private static final Map<String, Paste> pastes = new ConcurrentHashMap<>();
    private static final DelayQueue<Paste> delayQueue = new DelayQueue<>();

    //延迟队列实现过期删除
    static {
        new Thread(() -> {
            try {
                while (true) {
                    Paste paste = delayQueue.take();
                    pastes.remove(paste.getId());
                    log.info("Timeout: {}", paste);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    @Override
    public void add(Paste paste) {
        delayQueue.add(paste);
        pastes.put(paste.getId(), paste);
    }

    @Override
    public Paste getById(String key) {
        return pastes.getOrDefault(key, null);
    }
}
